package com.finger.crowd.controller;

import com.finger.crowd.api.MySQLRemoteService;
import com.finger.crowd.api.RedisRemoteService;
import com.finger.crowd.constant.CrowdConstant;
import com.finger.crowd.entity.po.MemberPO;
import com.finger.crowd.entity.vo.LoginMemberVO;
import com.finger.crowd.entity.vo.MemberVO;
import com.finger.crowd.util.CrowdUtils;
import com.finger.crowd.util.ResultEntity;
import com.google.gson.Gson;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Controller
public class MemberController {
    @Autowired
    private RedisRemoteService redisRemoteService;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Autowired
    private Gson gson;

    @Autowired
    private MySQLRemoteService sqlRemoteService;

    @ResponseBody
    @RequestMapping("/auth/member/send/short/message.json")
    public ResultEntity sendShortMessage(@RequestParam("phoneNum") String phoneNum) {
        ResultEntity<String> sendResultEntity = CrowdUtils.sendMessage(phoneNum);
        if ("SUCCESS".equals(sendResultEntity.getResult())) {
            ResultEntity<String> messageResultEntity = redisRemoteService.setRedisKeyValueRemoteWithTimeout(CrowdConstant.REDIS_PHONE_MESSAGE + phoneNum, "5873", 3, TimeUnit.MINUTES);
            String result = messageResultEntity.getResult();
            if ("SUCCESS".equals(result)) {
                return ResultEntity.successWithOutData();
            } else {
                return messageResultEntity;
            }
        } else {
            return sendResultEntity;
        }
    }


    // 登录
    @RequestMapping("/auth/do/member/regist")
    public String memberRegist(MemberVO memberVO,
                               Model model) {

        // 获取手机号
        String phone = memberVO.getPhone();

        // 拼从redis中的key
        String redisMessageCode = CrowdConstant.REDIS_PHONE_MESSAGE + phone;

        // 根据key从redis中获取验证码
        ResultEntity<String> redisStringValueByKeyRemote = redisRemoteService.getRedisStringValueByKeyRemote(redisMessageCode);

        // 验证验证码是否和输入的一致
        if (redisStringValueByKeyRemote.getResult() == "FAILED"
                || redisStringValueByKeyRemote.getData() == null
                || !Objects.equals(memberVO.getCode(), redisStringValueByKeyRemote.getData())) {
            model.addAttribute("message", "验证码错误");

            return "member-reg";
        }

        // 从redis中移除验证码
        redisRemoteService.removeRedisByKeyRemote(redisMessageCode);

        // 创建一个po对象
        MemberPO memberPO = new MemberPO();

        // 使用工具方法把vo对象转成po对象
        BeanUtils.copyProperties(memberVO, memberPO);

        String encodingUserPswd = passwordEncoder.encode(memberPO.getUserpswd());

        memberPO.setUserpswd(encodingUserPswd);

        // 保存
        ResultEntity<String> resultEntity = sqlRemoteService.saveMember(memberPO);

        // 如果返回的结果为failed说明用户名被占用
        if ("FAILED".equals(resultEntity.getResult())) {

            model.addAttribute("message", resultEntity.getMassage());

            return "member-reg";
        }

        return "redirect:member-login";

    }

    @RequestMapping("/auth/member/do/login")
    public String memberLogin(
            @RequestParam("loginacct") String loginacct,
            @RequestParam("userpswd") String userpswd,
            Model model,
            HttpSession session
    ) {
        ResultEntity<MemberPO> loginResultEntity = sqlRemoteService.loginAcct(loginacct);

        if ("FAILED".equals(loginResultEntity.getResult())) {
            model.addAttribute("message", "账号不存在");
            return "member-login";
        }

        String memberPOString = gson.toJson(loginResultEntity.getData());

        MemberPO memberPO = gson.fromJson(memberPOString, MemberPO.class);

        boolean matches = passwordEncoder.matches(userpswd, memberPO.getUserpswd());

        if (!matches) {
            model.addAttribute("message", "密码输入错误");
            return "member-login";
        }

        LoginMemberVO loginMemberVO = new LoginMemberVO();

        BeanUtils.copyProperties(memberPO, loginMemberVO);

        session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER, loginMemberVO);

        return "member";
    }

    @RequestMapping("/auth/member/do/logout")
    public String logoutMember(
            HttpSession session
    ) {
        session.invalidate();
        return "redirect:http://www.crowd.com";
    }
}
